import {
    getSearchHot,
    getSearchResult,
    getSearchSuggest
} from '../../service/search-api';

import string2nodes from '../../utils/string2nodes';
import debounce from '../../utils/debounce';

// 防抖操作
const debounceGetSearchSuggest = debounce(getSearchSuggest, 300);
Page({
    data: {
        searchHot: [],
        searchValue: '',

        // 搜索结果
        searchResult: [],

        // 根据关键字联想提示音乐
        suggestSongs: [],
        suggestSongsNodes: [],
    },

    // 请求数据
    async getPageData() {
        const res = await getSearchHot();
        this.setData({
            searchHot: res.result.hots
        })
    },

    async handleSearchChange(event) {
        const value = event.detail;
        if (value) {
            const res = await debounceGetSearchSuggest(value);
            this.setData({
                suggestSongs: res.result.allMatch,
            });
            const keywords = this.data.suggestSongs.map(info => info.keyword);
            const suggestSongsNodes = string2nodes(keywords, value);
            this.setData({
                suggestSongsNodes
            })
        } else {
            this.setData({
                suggestSongsNodes: [],
                suggestSongs: [],
                searchResult: []
            })
        }
        this.setData({
            searchValue: event.detail,
        })
    },

    // 获取搜索结果
    async getSearchResultHandle(event) {
        const keyword = event.currentTarget.dataset.keyword;
        this.setSearchResult(keyword);
    },

    // 回车进行搜索
    async getSuggestResult() {
        const keyword = this.data.searchValue;
        this.setSearchResult(keyword);
    },
    async setSearchResult(keyword) {
        const res = await getSearchResult(keyword);
        this.setData({
            searchResult: res.result.songs
        })
    },
    onLoad: function () {
        this.getPageData();
    }
})